package com.cyl.manager.oms.service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDeptService;

import io.swagger.annotations.ApiModelProperty;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cyl.h5.config.SecurityUtil;
import com.cyl.manager.oms.domain.dto.OrderItemPrepareDTO;
import com.cyl.manager.oms.domain.entity.OrderItemPrepare;
import com.cyl.manager.oms.domain.entity.OrderLock;
import com.cyl.manager.oms.domain.query.OrderLockQuery;
import com.cyl.manager.oms.domain.vo.OrderAmoutVO;
import com.cyl.manager.oms.domain.vo.OrderItemPrepareExcelVO;
import com.cyl.manager.oms.mapper.OrderItemMapper;
import com.cyl.manager.oms.mapper.OrderItemPrepareMapper;
import com.cyl.manager.oms.mapper.OrderLockMapper;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.pms.domain.entity.Product;
import com.cyl.manager.pms.domain.entity.Sku;
import com.cyl.manager.pms.service.ProductService;
import com.cyl.manager.pms.service.SkuService;

/**
 * 锁单管理Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class OrderLockService {
    @Autowired
    private OrderLockMapper orderLockMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderItemPrepareMapper orderItemPrepareMapper;
    
    
    @Autowired
    private ISysDeptService deptService;
    
    

    @Autowired
    private SkuService skuService;
    @Autowired
    private ProductService productService;
    
    /**
     * 查询锁单管理
     *
     * @param id 锁单管理主键
     * @return 锁单管理
     */
    public OrderLock selectById(Long id) {
        return orderLockMapper.selectById(id);
    }

    /**
     * 查询锁单管理列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 锁单管理
     */
    public List<OrderLock> selectList(OrderLockQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<OrderLock> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        Long deptZbjId = query.getDeptZbjId();
        if (deptZbjId != null) {
            qw.eq("dept_zbj_id", deptZbjId);
        }
        LocalDateTime startTime = query.getStartTime();
        if (startTime != null) {
            qw.eq("start_time", startTime);
        }
        LocalDateTime endTime = query.getEndTime();
        if (endTime != null) {
            qw.eq("end_time", endTime);
        }
        Integer deptDpNum = query.getDeptDpNum();
        if (deptDpNum != null) {
            qw.eq("dept_dp_num", deptDpNum);
        }
        Integer skuNum = query.getSkuNum();
        if (skuNum != null) {
            qw.eq("sku_num", skuNum);
        }
        Integer orderNum = query.getOrderNum();
        if (orderNum != null) {
            qw.eq("order_num", orderNum);
        }
        Integer sdzt = query.getSdzt();
        if (sdzt != null) {
            qw.eq("sdzt", sdzt);
        }
        return orderLockMapper.selectList(qw);
    }

    /**
     * 新增锁单管理
     *
     * @param orderLock 锁单管理
     * @return 结果
     */
    public int insert(OrderLock orderLock) {
        orderLock.setDelFlag(0);
        orderLock.setSdzt(0);
        orderLock.setCreateTime(LocalDateTime.now());
        return orderLockMapper.insert(orderLock);
    }

    /**
     * 修改锁单管理
     *
     * @param orderLock 锁单管理
     * @return 结果
     */
    @Transactional
    public int startOrderLock(Long lockId) {
     	Map<Long, SysDept> mapSysDept = new HashMap<Long, SysDept>();
     	Map<Long, SysDept> mapSysDp = new HashMap<Long, SysDept>();

    	Map<Long, Sku> mapSku = new HashMap<Long, Sku>();
    	Map<Long, Product> mapProduct = new HashMap<Long, Product>();


    	OrderLock orderLock =  orderLockMapper.selectById(lockId);
    	if(orderLock==null) {
            throw new RuntimeException("锁单不存在");
    	}
    	if(orderLock.getSdzt().intValue() == 1 ) {
            throw new RuntimeException("已锁单不能重复操作！");
    	}
    	LocalDateTime thisTime = LocalDateTime.now();
    	orderMapper.orderLock(orderLock.getStartTime(), orderLock.getEndTime(), orderLock.getDeptZbjId(), lockId);
    	List<OrderItemPrepare> listOips =  orderItemMapper.findOrderItemPrepares(lockId, orderLock.getDeptZbjId());
    	int skusum = 0;
        if(listOips!=null && listOips.size() > 0) {
        	for (OrderItemPrepare orderItemPrepare : listOips) {
        		Long deptDpId = orderItemPrepare.getDeptDpId();
    			Long deptZbjId = orderItemPrepare.getDeptZbjId();
    			
    			Long skuId = orderItemPrepare.getSkuId();
    			Long productId = orderItemPrepare.getProductId();
    			Sku sku = null;
    			Product product= null;
    			SysDept deptDp = null;
    			SysDept deptZb = null;
    			
    			if(mapSku.containsKey(skuId)) {
    				sku = mapSku.get(skuId);
    			}else {
    				sku =  skuService.selectById(skuId);
    				mapSku.put(skuId, sku);
    			}
    			
    			if(mapProduct.containsKey(productId)) {
    				product = mapProduct.get(productId);
    			}else {
    				product = productService.getById(productId);
    				mapProduct.put(productId, product);
    			}
    			
    			
    			if(mapSysDp.containsKey(deptDpId)) {
    				deptDp = mapSysDp.get(deptDpId);
    			}else { 
        			deptDp =  deptService.getCacheSysDept(deptDpId);
        			mapSysDp.put(deptDpId, deptDp);
    			}
    			
    			
    			if(mapSysDept.containsKey(deptZbjId)) {
    				deptZb = mapSysDept.get(deptZbjId);
    			}else {
        			deptZb = deptService.getCacheSysDept(deptZbjId);
        			mapSysDept.put(deptZbjId, deptZb);
    			}
    			
        		Long userid = SecurityUtils.getUserId();
        		orderItemPrepare.setCreateTime(thisTime);
                orderItemPrepare.setCreateBy(userid);
                orderItemPrepare.setUpdateTime(thisTime);
                orderItemPrepare.setUpdateBy(userid);
        		orderItemPrepare.setDelFlag(0);
        		orderItemPrepare.setStartTime(orderLock.getStartTime());
        		orderItemPrepare.setEndTime(orderLock.getEndTime());
        		orderItemPrepare.setBhZt("1");
        		orderItemPrepare.setLockId(lockId);

        		orderItemPrepare.setDeptZbjMc(deptZb.getDeptName());
        		orderItemPrepare.setDeptDpMc(deptDp.getDeptName());
        		orderItemPrepare.setDpdh(deptDp.getPhone());
        		orderItemPrepare.setDplxr(deptDp.getLeader());
        		orderItemPrepare.setAddress(deptDp.getProvince()+"-"+deptDp.getCity()+"-"+deptDp.getDistrict()+"-"+ deptDp.getAddress());
        		
        		if(product!=null) {
					orderItemPrepare.setPic(product.getPic());
    				orderItemPrepare.setProductName(product.getName());
    			}
        		if(sku!=null) {
    				orderItemPrepare.setSpData(sku.getSpData());
    				if(sku.getPic()!=null && sku.getPic().length()>5) {
    					orderItemPrepare.setPic(sku.getPic());
    				}
    			}
    			Long sNum = orderItemPrepare.getSkuSum();
    			if(sNum!=null) {
        			skusum = skusum+ sNum.intValue();
    			}
    		 
        		orderItemPrepareMapper.insert(orderItemPrepare);
        		Long prepareId =  orderItemPrepare.getId();

        		orderItemMapper.orderItemLock(deptDpId,lockId, prepareId,productId, skuId);
        		OrderAmoutVO orderAmoutVO = orderMapper.getOrderAmount(lockId, prepareId);
        		orderItemPrepareMapper.updateOrdernum(prepareId,orderAmoutVO.getOrdersum(),orderAmoutVO.getPayAmount());
			}
        }
       
		OrderAmoutVO oAmoutVO = orderMapper.getOrderAmount(lockId, null);
    	orderLock.setZordernum(listOips.size());
        orderLock.setSkuNum(mapSku.size()); 
        orderLock.setDeptDpNum(mapSysDp.size());
        orderLock.setOrderNum(oAmoutVO.getOrdersum());
        orderLock.setSkusum(skusum);
        orderLock.setSumprice(oAmoutVO.getPayAmount());
        orderLock.setSdzt(1);
    	return orderLockMapper.updateById(orderLock);
    }
    
    /**
     * 修改锁单管理
     *
     * @param orderLock 锁单管理
     * @return 结果
     */
    public int update(OrderLock orderLock) {
        return orderLockMapper.updateById(orderLock);
    }

    /**
     * 批量删除锁单管理
     *
     * @param ids 需要删除的锁单管理主键
     * @return 结果
     */
    public int deleteByIds(Long[] ids) {
        return orderLockMapper.updateDelFlagByIds(ids);
    }

    /**
     * 删除锁单管理信息
     *
     * @param id 锁单管理主键
     * @return 结果
     */
    public int deleteById(Long id) {
        Long[] ids = {id};
        return orderLockMapper.updateDelFlagByIds(ids);
    }
}
